import { AppDataSource } from "@/config/database";
import { Services } from "@/entities/basis/services.entity";
import { ErrorHandler } from "@/middlewares/error.middleware";
import { Context } from "koa";

/** 删除服务 */
export async function deleteService(ctx: Context) {
    const { id } = ctx.params;

    // 验证参数
    validateParams(id);

    // 检查服务是否存在
    const service = await checkServiceExists(id);

    // 执行软删除
    await softDeleteService(service);

    ctx.status = 200;
    ctx.body = { message: '服务删除成功' };
}

/** 验证参数 */
const validateParams = (id: string) => {
    if (!id) {
        throw new ErrorHandler('服务ID不能为空', 400);
    }
}

/** 检查服务是否存在 */
const checkServiceExists = async (id: string) => {
    const serviceRepository = AppDataSource.getRepository(Services);
    
    const service = await serviceRepository.findOne({
        where: { id }
    });
    
    if (!service) {
        throw new ErrorHandler('服务不存在', 404);
    }
    
    return service;
}

/** 软删除服务 */
const softDeleteService = async (service: Services) => {
    const serviceRepository = AppDataSource.getRepository(Services);
    
    // 软删除：设置删除时间
    service.deletedAt = new Date();
    
    try {
        await serviceRepository.save(service);
    } catch (error) {
        throw new ErrorHandler('删除服务失败', 500);
    }
} 